﻿using NModbus;
using System.ComponentModel;
using System.IO.Ports;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Text;
using NModbus.Extensions.Enron;
using NModbus.Serial;
using System.Threading;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Markup;

namespace MCPlatform.Communicate.Modbus.Modbus
{
    public class RTUMaster: IDisposable, INotifyPropertyChanged
    {
        NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        private  ModbusFactory modbusFactory;
        private  IModbusMaster? master;

        public event Action<object, string>? MasterErrorEvent;


        private Thread? _rxThread = null;

        public bool IsRetryConnect { get; set; } = false;

        //重连次数
        public int RetryCount { get; set; } = 0;
        internal bool QueueStop { get; set; }

        public bool IsConnected { 
            get 
            {
                //if (masterClient!=null)
                //{
                //    return masterClient.Connected && masterConnected;
                //}
                //return false;
                if (master == null  || !masterConnected || !ClientConnected)// ||
                   // masterClient.Client.Poll(1, SelectMode.SelectRead) == true) && masterTcpClient.Available == 0)
                {
                    return false;
                }
                return true;
            }
           
        }

        /// <summary>
        /// 辅助连接属性，主要是为了防止TCP 连接句柄成功，但实际从站地址未开放，导致读取从站失败
        /// </summary>
        public bool ClientConnected
        {
            get;
            set;
        } = true;


        private bool connected;

        public bool Connected
        {
            get { return connected; }
            set { connected = value; RaisePropertyChanged(); }
        }

        private bool masterConnected=false;

        public ModbusRTUMasterInfo ModbusRTUMasterInfo { get; set; }

        
        public string? SlaveName
        {
            get { return ModbusRTUMasterInfo.SlaveName; }
            //set { ModbusRTUMasterInfo.SlaveName = value; }
        }

        public event PropertyChangedEventHandler? PropertyChanged;

        protected void RaisePropertyChanged([CallerMemberName] string? name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        public void Set<T>(ref T field, T value, [CallerMemberName] string propName = "")
        {
            if (EqualityComparer<T>.Default.Equals(field, value))
            {
                return;
            }
            field = value;
            RaisePropertyChanged(propName);
        }
        //读取超时时间
     //   int readTimeout = 200;
        //重试时间
      //  int retryTimeout = 2;

        /// <summary>
        /// Modbus 主站是客户端，从站是服务器
        /// </summary>
       
        public RTUMaster(ModbusRTUMasterInfo modbusRTUMasterInfo)
        {
            modbusFactory = new ModbusFactory();
            ModbusRTUMasterInfo = modbusRTUMasterInfo;  
         
           
        }

        /// <summary>
        /// 连接从站，也就是连接服务器
        /// </summary>
        public  async Task<bool> Connection()
        {
           await Task.Run(() =>
            {
                try
                {
                    StartRxThread();

                    if (ModbusRTUMasterInfo is null || ModbusRTUMasterInfo.Port is null)
                    {
                        return false;
                    }
                    SerialPort port = ModbusRTUMasterInfo.Port;
                    port.Open();

                    // Wrap the serial port
                    var adapter = new SerialPortAdapter(port);



                    // Create Modbus Master
                    master = modbusFactory.CreateRtuMaster(adapter);

                    masterConnected = true;
                    logger.Info($"RTUMaster {ModbusRTUMasterInfo.SlaveName}Connect,port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                    return true;
                }
                catch (Exception)
                {
                    masterConnected = false;
                    logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}Connect fail,port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                    return false;
                }
            });
         
            return masterConnected; 
            
               
          
        }

        public bool ReConnection()
        {
           
                try
                {

                    if (ModbusRTUMasterInfo is null || ModbusRTUMasterInfo.Port is null)
                    {
                        return false;
                    }

                    SerialPort port = ModbusRTUMasterInfo.Port;
                    port.Open();

                    // Wrap the serial port
                    var adapter = new SerialPortAdapter(port);



                    // Create Modbus Master
                    master = modbusFactory.CreateRtuMaster(adapter);
                    masterConnected = true;
                    logger.Info($"RTUMaster {ModbusRTUMasterInfo.SlaveName}ReConnect,port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                    return true;
                }
                catch (Exception)
                {
                    masterConnected = false;
                    logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}ReConnect fail,port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                    return false;
                }
          
        



        }



        private void StartRxThread()
        {
            if (_rxThread == null)
            {
                _rxThread = new Thread(new ParameterizedThreadStart(ListenerLoop));
                _rxThread.IsBackground = true;
                _rxThread.Start();
            }
        }

        private void ListenerLoop(object? state)
        {
            while (!QueueStop)
            {
                try
                {
                    RunLoopStep();
                    IsRetryConnect = this.ModbusRTUMasterInfo.IsAutoRetry;
                    Connected = this.IsConnected;
                    if (Connected)
                    {
                        RetryCount = 0;
                    }

                }
                catch
                {

                }

                Thread.Sleep(100);
            }

            _rxThread = null;
        }

        private async void RunLoopStep()
        {
            if ((master == null || !this.IsConnected) && !IsRetryConnect)
            {
                return;
            }
            else if (IsRetryConnect && (!this.IsConnected))//尝试重连
            {
                // Disconnect();
                // Thread.Sleep(20000);
                if (RetryCount >= 10) //重连10次
                {
                    return;
                }
                ReConnection();
                RetryCount++;
                await Task.Delay(2000);//延迟5s
            }
        }

        public bool Disconnect()
        {
            try
            {
                if (ModbusRTUMasterInfo is null || ModbusRTUMasterInfo.Port is null) 
                { 
                    return false; 
                }
                //masterClient.Close();//关闭客户端
                ModbusRTUMasterInfo?.Port.Close();
                masterConnected = false;
                logger.Info($"RTUMaster {ModbusRTUMasterInfo?.SlaveName}Disconncet,port:{ModbusRTUMasterInfo?.Port},slaveName:{ModbusRTUMasterInfo?.SlaveName}");
                return true;
            }
            catch (Exception)
            {
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}Disconnect fail,port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                return false;
            }
        }

        /// <summary>
        /// 读取从站线圈值
        /// </summary>
        /// <param name="startAddress">线圈起始地址</param>
        /// <param name="numberOfPoints">长度</param>
        /// <returns></returns>
        public async Task<bool[]?> ReadCoilsAsync(ushort startAddress, ushort numberOfPoints)
        {
            try
            {
                if (master is null) return null;
                
                return await master.ReadCoilsAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, numberOfPoints);
            }
            catch (Exception ex)
            {
                // masterConnected = false;
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveName + ex.Message);
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}ReadCoils fail,startAddress:{startAddress},numberOfPoints:{numberOfPoints},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                return new bool[numberOfPoints];
            }


        }
        /// <summary>
        /// 读取从站线圈值
        /// </summary>
        /// <param name="startAddress">线圈起始地址</param>
        /// <param name="numberOfPoints">长度</param>
        /// <returns></returns>
        public bool[]? ReadCoils(ushort startAddress,ushort numberOfPoints)
        {
            try
            {
                if (master is null) return null;
                return master.ReadCoils(ModbusRTUMasterInfo.SlaveAddr, startAddress, numberOfPoints);
            }
            catch (Exception ex)
            {
               // masterConnected = false;
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveName + ex.Message);
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}ReadCoils fail,startAddress:{startAddress},numberOfPoints:{numberOfPoints},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                return new bool[numberOfPoints];
            }
           

        }

        /// <summary>
        /// 读取从站输入值
        /// </summary>
        /// <param name="startAddress">从站输入起始地址</param>
        /// <param name="numberOfPoints">长度</param>
        /// <returns></returns>
        public bool[]? ReadInputs(ushort startAddress, ushort numberOfPoints)
        {
            try
            {
                if (master is null) return null;
                return master.ReadInputs(ModbusRTUMasterInfo.SlaveAddr, startAddress, numberOfPoints);
            }
            catch (Exception ex)
            {
              //  masterConnected = false;
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}ReadInputs fail,startAddress:{startAddress},numberOfPoints:{numberOfPoints},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveName + ex.Message);
                return new bool[numberOfPoints];
            }
           
           

        }

        /// <summary>
        /// 读取从站寄存器值
        /// </summary>
        /// <param name="startAddress">寄存器起始地址</param>
        /// <param name="numberOfPoints">长度</param>
        /// <returns></returns>
        /// 
        public async Task<ushort[]?> ReadHoldingRegistersAsync(ushort startAddress, ushort numberOfPoints,int timeOutMs=2000)
        {
            try
            {
                if (master is null)
                {
                    throw new ArgumentNullException("Master is null");
                }

                // return await master.ReadHoldingRegistersAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, numberOfPoints);

                var cts = new CancellationTokenSource();

                // 设置一个较短的超时时间
                var timeoutTask = Task.Delay(timeOutMs, cts.Token);

                var readTask = master.ReadHoldingRegistersAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, numberOfPoints);

                Task completedTask = await Task.WhenAny(readTask, timeoutTask);

                if (completedTask == readTask && readTask.Status == TaskStatus.RanToCompletion)
                {
                    // 读取成功，处理读取到的数据
                    ushort[] result = readTask.Result;
                    return result;
                }
                else if (completedTask == readTask && readTask.Status != TaskStatus.RanToCompletion)
                {
                    // 处理异步操作未成功完成的情况
                    // Console.WriteLine("Read operation failed to complete.");
                    throw new TimeoutException();
                }
                else if (completedTask == timeoutTask)
                {
                    // 超时处理
                    // Console.WriteLine("Read operation timed out.");
                    // 如果在超时时取消任务
                    cts.Cancel();

                    throw new TimeoutException();
                }
                else
                {
                    // 超时处理
                    //master.Dispose();
                    //await this.Connection();
                    throw new TimeoutException();


                }


            }
            catch (Exception ex)
            {
                // masterConnected = false;
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveAddr + ex.Message);
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}ReadHoldingRegisters fail,startAddress:{startAddress},numberOfPoints:{numberOfPoints},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                return null;
            }
        }
     
        public async Task<long[]?> ReadHoldingRegistersWithLongAsync(ushort startAddress, ushort numberOfPoints, int timeOutMs=2000)
        {
            try
            {
                if (master is null)
                {
                    throw new ArgumentNullException("Master is null");
                }

                if (numberOfPoints % 2 != 0)
                {
                    numberOfPoints++;
                }

               

                using (var cts = new CancellationTokenSource())
                {
                    // 设置一个较短的超时时间
                    var timeoutTask = Task.Delay(timeOutMs, cts.Token);

                    var readTask = master.ReadHoldingRegistersAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, numberOfPoints);

                    Task completedTask = await Task.WhenAny(readTask, timeoutTask);

                    if (completedTask == readTask && readTask.Status == TaskStatus.RanToCompletion)
                    {
                        // 读取成功，处理读取到的数据
                        ushort[] result = await readTask; // 注意：这里可能抛出异常，需要适当处理

                        List<long> longData = new List<long>();

                        for (int i = 0; i < result.Length; i = i + 2)
                        {
                            // 将ushort数组中的两个元素交换位置，实现CDAB顺序
                            int longValue = (int)((result[i] << 16) | result[i + 1]);

                            longData.Add(longValue);
                        }

                        return longData.ToArray();

                    }
                    else if (completedTask == readTask && readTask.Status != TaskStatus.RanToCompletion)
                    {
                        // 处理异步操作未成功完成的情况
                        logger.Error("Read operation failed to complete.");
                        return null;
                      //  throw new TimeoutException();
                    }
                    else if (completedTask == timeoutTask)
                    {
                        // 超时处理
                        logger.Error("Read operation timed out.");
                        // 如果在超时时取消任务
                        cts.Cancel();
                        return null;
                       // throw new TimeoutException();
                    }
                    else
                    {
                        // 超时处理
                        //master.Dispose();
                        //await this.Connection();
                        logger.Error("Read operation timed out.");
                        return null;
                       // throw new TimeoutException();


                    }

                }
              



            }
            catch (Exception ex)
            {
                // masterConnected = false;
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveAddr + ex.Message);
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}ReadHoldingRegisters fail,startAddress:{startAddress},numberOfPoints:{numberOfPoints},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                return new long[numberOfPoints];
            }

        }

        public async Task<long[]> ReadHoldingRegistersWithLongABCDAsync(ushort startAddress, ushort numberOfPoints)
        {
            try
            {
                if (master is null)
                {
                    throw new ArgumentNullException("Master is null");
                }

                if (numberOfPoints % 2 != 0)
                {
                    numberOfPoints++;
                }

                var result = await master.ReadHoldingRegistersAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, numberOfPoints);

                List<long> longData = new List<long>();

                for (int i = 0; i < result.Length; i = i + 2)
                {
                    int longValue = (int)((result[i] << 16) | result[i+1]);

                    longData.Add(longValue);

                }

                return longData.ToArray();
            }
            catch (Exception ex)
            {
                // masterConnected = false;
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveAddr + ex.Message);
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}ReadHoldingRegisters fail,startAddress:{startAddress},numberOfPoints:{numberOfPoints},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                return new long[numberOfPoints];
            }

        }

        public async Task<string[]?> ReadHoldingRegistersByHexAsync(ushort startAddress, ushort numberOfPoints)
        {
            try
            {
                if (master is null) return null;
                var result = await master.ReadHoldingRegistersAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, numberOfPoints);
                string[] registers = UShortArrayToHexArray(result);
                return registers;
            }
            catch (Exception ex)
            {
                // masterConnected = false;
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveAddr + ex.Message);
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}ReadHoldingRegisters fail,startAddress:{startAddress},numberOfPoints:{numberOfPoints},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                return new string[numberOfPoints];
            }

        }

        public async Task<string?> ReadHoldingSingleRegistersByHexAsync(ushort startAddress)
        {
            try
            {
                if (master is null) return null;
                var result = await master.ReadHoldingRegistersAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress,1);
                string[] registers = UShortArrayToHexArray(result);
                return registers[0];
            }
            catch (Exception ex)
            {
                // masterConnected = false;
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveAddr + ex.Message);
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}ReadHoldingRegisters fail,startAddress:{startAddress},numberOfPoints:{1},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                return String.Empty;
            }

        }

        public async Task<string?> ReadHoldingSingleRegistersByBinaryAsync(ushort startAddress)
        {
            try
            {
                if (master is null) return null;
                var result = await master.ReadHoldingRegistersAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, 1);
                string binaryString = Convert.ToString(result[0], 2);
                return binaryString;
            }
            catch (Exception ex)
            {
                // masterConnected = false;
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveAddr + ex.Message);
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}ReadHoldingRegisters fail,startAddress:{startAddress},numberOfPoints:{1},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                return String.Empty;
            }

        }

        // 将ushort数组转换为16进制字符串数组的方法
        static string[] UShortArrayToHexArray(ushort[] ushortArray)
        {
            string[] hexArray = new string[ushortArray.Length];

            for (int i = 0; i < ushortArray.Length; i++)
            {
                hexArray[i] = ushortArray[i].ToString("X4"); // 使用"X4"格式将ushort转换为4位16进制字符串
            }

            return hexArray;
        }
        public  ushort[] ReadHoldingRegisters(ushort startAddress, ushort numberOfPoints)
        {
            try
            {
                if (master is null)
                {
                    throw new ArgumentNullException("Master is null");
                }
                var result =  master.ReadHoldingRegisters(ModbusRTUMasterInfo.SlaveAddr, startAddress, numberOfPoints);
                return result;
            }
            catch (Exception ex)
            {
                // masterConnected = false;
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveAddr + ex.Message);
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}ReadHoldingRegisters fail,startAddress:{startAddress},numberOfPoints:{numberOfPoints},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                return new ushort[numberOfPoints];
            }

        }
        /// <summary>
        /// 读取从站寄存器值
        /// </summary>
        /// <param name="startAddress">寄存器起始地址</param>
        /// <param name="numberOfPoints">长度</param>
        /// <returns></returns>
        public async Task<float[]?> ReadHoldingRegistersWithFloatAsync(ushort startAddress, ushort numberOfPoints)
        {
            try
            {
                if (numberOfPoints % 2 != 0)
                {
                    numberOfPoints++;
                }
                if (master is null) return null;
                var data = await master.ReadHoldingRegistersAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, numberOfPoints);
                List<float> floatData = new List<float>();

                for (int i = 0; i < data.Length; i = i + 2)
                {
                    floatData.Add(GetReal(data, i));
                    floatData.Add(0.0f);

                }

                return floatData.ToArray();

            }
            catch (Exception ex)
            {
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveAddr + ex.Message);
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}ReadHoldingRegisters fail,startAddress:{startAddress},numberOfPoints:{numberOfPoints},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                return new float[numberOfPoints];
            }

        }
        /// <summary>
        /// 读取从站寄存器值
        /// </summary>
        /// <param name="startAddress">寄存器起始地址</param>
        /// <param name="numberOfPoints">长度</param>
        /// <returns></returns>
        public float[]? ReadHoldingRegistersWithFloat(ushort startAddress, ushort numberOfPoints)
        {
            try
            {
                if (numberOfPoints % 2 != 0)
                {
                    numberOfPoints++;
                }
                if (master is null) return null;
                var data = master.ReadHoldingRegisters(ModbusRTUMasterInfo.SlaveAddr, startAddress, numberOfPoints);
                List<float> floatData = new List<float>();

                for (int i = 0; i < data.Length; i=i+2)
                {
                    floatData.Add(GetReal(data, i));
                    floatData.Add(0.0f);

                }
               
                return floatData.ToArray(); 

            }
            catch (Exception ex)
            {
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveAddr + ex.Message);
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}ReadHoldingRegisters fail,startAddress:{startAddress},numberOfPoints:{numberOfPoints},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                return new float[numberOfPoints];
            }

        }

        /// <summary>
        /// 读取从站寄存器值
        /// </summary>
        /// <param name="startAddress">寄存器起始地址</param>
        /// <param name="numberOfPoints">长度</param>
        /// <returns></returns>
        public async Task<float[]?> ReadHoldingRegistersWithFloatABCDAsync(ushort startAddress, ushort numberOfPoints)
        {
            try
            {
                if (numberOfPoints % 2 != 0)
                {
                    numberOfPoints++;
                }
                if (master is null) return null;
                var data = await master.ReadHoldingRegistersAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, numberOfPoints);
                List<float> floatData = new List<float>();

                for (int i = 0; i < data.Length; i = i + 2)
                {
                    floatData.Add(GetRealABCD(data, i));
                    floatData.Add(0.0f);

                }

                return floatData.ToArray();

            }
            catch (Exception ex)
            {
                masterConnected = false;
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveAddr + ex.Message);
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}ReadHoldingRegisters fail,startAddress:{startAddress},numberOfPoints:{numberOfPoints},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                return new float[numberOfPoints];
            }

        }
        /// <summary>
        /// 读取从站寄存器值
        /// </summary>
        /// <param name="startAddress">寄存器起始地址</param>
        /// <param name="numberOfPoints">长度</param>
        /// <returns></returns>
        public float[]? ReadHoldingRegistersWithFloatABCD(ushort startAddress, ushort numberOfPoints)
        {
            try
            {
                if (numberOfPoints % 2 != 0)
                {
                    numberOfPoints++;
                }
                var data = master?.ReadHoldingRegisters(ModbusRTUMasterInfo.SlaveAddr, startAddress, numberOfPoints);
                List<float> floatData = new List<float>();
                if (data is null) return null;
                for (int i = 0; i < data.Length; i = i + 2)
                {
                    floatData.Add(GetRealABCD(data, i));
                    floatData.Add(0.0f);

                }

                return floatData.ToArray();

            }
            catch (Exception ex)
            {
                masterConnected = false;
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveAddr + ex.Message);
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}ReadHoldingRegisters fail,startAddress:{startAddress},numberOfPoints:{numberOfPoints},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                return new float[numberOfPoints];
            }

        }
        /// <summary>
        /// 读取从站输入寄存器值，PLC做从站的话，一般是输入模拟量的值
        /// </summary>
        /// <param name="startAddress">输入寄存器起始地址</param>
        /// <param name="numberOfPoints">长度，就是要读几个模拟量的值</param>
        /// <returns></returns>
        public ushort[]? ReadInputRegisters(ushort startAddress, ushort numberOfPoints)
        {
            try
            {
                if (master is null) return null;
                return master.ReadInputRegisters(ModbusRTUMasterInfo.SlaveAddr, startAddress, numberOfPoints);
            }
            catch (Exception ex)
            {
                masterConnected = false;
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveName + ex.Message);
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}ReadInputRegisters fail,startAddress:{startAddress},numberOfPoints:{numberOfPoints},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                return new ushort[numberOfPoints];
            }
           

        }

        /// <summary>
        /// 写从站单个线圈值
        /// </summary>
        /// <param name="startAddress">线圈起始地址</param>
        /// <param name="value">要写的地址值</param>
        public async void WriteSingleCoilAsync(ushort startAddress, bool value)
        {
            try
            {
                if (master is null)
                {
                    return;
                }
                await master.WriteSingleCoilAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, value);
                if (startAddress != 8237)
                {
                    logger.Info($"RTUMaster {ModbusRTUMasterInfo.SlaveName}WriteSingleCoilAsync,startAddress:{startAddress},value:{value},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                }
               
            }
            catch (Exception ex)
            {
                masterConnected = false;
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}WriteSingleCoilAsync fail,startAddress:{startAddress},value:{value},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveName + ex.Message);
            }
           
        }

        /// <summary>
        /// 写单个寄存器值
        /// </summary>
        /// <param name="startAddress">寄存器起始地址</param>
        /// <param name="value">写的地址值</param>
        public async void WriteSingleRegisterAsync(ushort startAddress, ushort value)
        {
            try
            {
                // 创建一个用于等待的 Task
                if (master is null) return;
                
                var writeTask =  master.WriteSingleRegisterAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, value);

                // 使用 Task.WhenAny 等待任务完成或超时
                var completedTask = await Task.WhenAny(writeTask, Task.Delay(2000));

                // 检查任务的状态
                if (completedTask == writeTask)
                {
                    // 写入成功
                    logger.Info("写入成功");
                }
                else
                {
                    // 超时
                   logger.Error("写入超时");
                   this.Disconnect();
                   await this.Connection();
                }
                // ushort[] singleRegisterBuffer = new ushort[1];
                //singleRegisterBuffer[0] = value;
              //  await master.WriteSingleRegisterAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, value);
                // await master.WriteMultipleRegistersAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, singleRegisterBuffer);
                logger.Info($"RTUMaster {ModbusRTUMasterInfo.SlaveName}WriteSingleRegisterAsync,startAddress:{startAddress},value:{value},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
            }
            catch (Exception ex)
            {
                masterConnected = false;
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}WriteSingleRegisterAsync fail,startAddress:{startAddress},value:{value},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveName + ex.Message);
            }

        }


        public  void WriteSingleRegister(ushort startAddress, ushort value)
        {
            try
            {
                // ushort[] singleRegisterBuffer = new ushort[1];
                //singleRegisterBuffer[0] = value;
                if (master is null) return;
                master.WriteSingleRegister(ModbusRTUMasterInfo.SlaveAddr, startAddress, value);
                // await master.WriteMultipleRegistersAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, singleRegisterBuffer);
                logger.Info($"RTUMaster {ModbusRTUMasterInfo.SlaveName}WriteSingleRegister,startAddress:{startAddress},value:{value},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
            }
            catch (Exception ex)
            {
                masterConnected = false;
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}WriteSingleRegister fail,startAddress:{startAddress},value:{value},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveName + ex.Message);
            }

        }

        public async Task<(bool,string)> WriteSingleRegisterAsyncAndGetReply(ushort startAddress, string hex,int timeOut=2000)
        {
            try
            {

                ushort value = Convert.ToUInt16(hex, 16);
                if (master is null)
                {

                    logger.Error("master is null");
                    return (false,"master is null");
                }

                if (startAddress >= 40000)
                {
                    startAddress = (ushort)(startAddress - 40000);
                }


                // 创建一个用于等待的 Task
                var writeTask = master.WriteSingleRegisterAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, value);

                // 使用 Task.WhenAny 等待任务完成或超时
                var completedTask = await Task.WhenAny(writeTask, Task.Delay(timeOut));

                // 检查任务的状态
                if (completedTask == writeTask)
                {
                    // 写入成功
                    logger.Info("写入成功");
                    return (true,"done");
                }
                else
                {
                    // 超时
                    logger.Error("写入超时");
                    this.Disconnect();
                    await Task.Delay(500);
                    await this.Connection();
                    return (false,"write time out");
                }


                
            }
            catch (Exception ex)
            {
                masterConnected = false;
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}WriteSingleRegisterAsync fail,startAddress:{startAddress},value:{hex},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                logger.Error($"{ex.Message}");
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveName + ex.Message);
            }

            return (false, "write error");

        }
        public async void WriteSingleRegisterAsync(ushort startAddress, string hex)
        {
            try
            {
                
                ushort value = Convert.ToUInt16(hex, 16);
                if (master is null)
                {
                    throw new ArgumentNullException("Master is null");
                }

                if (startAddress >= 40000)
                {
                    startAddress = (ushort)(startAddress - 40000);
                }
            

                // 创建一个用于等待的 Task
                var writeTask = master.WriteSingleRegisterAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, value);

                // 使用 Task.WhenAny 等待任务完成或超时
                var completedTask = await Task.WhenAny(writeTask, Task.Delay(2000));

                // 检查任务的状态
                if (completedTask == writeTask)
                {
                    // 写入成功
                    logger.Info("写入成功");
                }
                else
                {
                    // 超时
                    logger.Error("写入超时");
                    master.Dispose();
                    await this.Connection();
                }


                logger.Info($"RTUMaster {ModbusRTUMasterInfo.SlaveName}WriteSingleRegisterAsync,startAddress:{startAddress},value:{hex},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
            }
            catch (Exception ex)
            {
                masterConnected = false;
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}WriteSingleRegisterAsync fail,startAddress:{startAddress},value:{hex},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                logger.Error($"{ex.Message}");
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveName + ex.Message);
            }

        }

        /// <summary>
        /// 写单个寄存器值
        /// </summary>
        /// <param name="startAddress">寄存器起始地址</param>
        /// <param name="value">写的地址值</param>
        public async void WriteSingleRegisterAsync(ushort startAddress, float value)
        {
            try
            {
                ushort[] buff = new ushort[2];
                SetReal(buff, 0, value);
                if (master is null) return;
                await master.WriteMultipleRegistersAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, buff);
                //  await master.WriteSingleRegisterAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, value);
                logger.Info($"RTUMaster {ModbusRTUMasterInfo.SlaveName}WriteSingleRegisterAsync,startAddress:{startAddress},value:{value},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
            }
            catch (Exception ex)
            {
                masterConnected = false;
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}WriteSingleRegisterAsync fail,startAddress:{startAddress},value:{value},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveName + ex.Message);
            }

        }

      

        /// <summary>
        /// 写从站多个线圈值
        /// </summary>
        /// <param name="startAddress">起始地址</param>
        /// <param name="data">地址值数组</param>
        public async void WriteMultipleCoilsAsync(ushort startAddress, bool[] data)
        {
            try
            {
                if (master is null) return ;
                await master.WriteMultipleCoilsAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, data);
                logger.Info($"RTUMaster {ModbusRTUMasterInfo.SlaveName}WriteMultipleCoilsAsync,startAddress:{startAddress},data:{data},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
            }          
          
            catch (Exception ex)
            {
                masterConnected = false;
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}WriteMultipleCoilsAsync fail,startAddress:{startAddress},data:{data},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveName + ex.Message);
            }
        }

        

        /// <summary>
        /// 写从站多个寄存器值
        /// </summary>
        /// <param name="startAddress">起始地址</param>
        /// <param name="data">地址值数组</param>
        public async void WriteMultipleRegistersAsync(ushort startAddress, ushort[] data)
        {
            
            try
            {
                if (master is null) return;
                await master.WriteMultipleRegistersAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, data);
                logger.Info($"RTUMaster {ModbusRTUMasterInfo.SlaveName}WriteMultipleRegistersAsync,startAddress:{startAddress},data:{string.Join(",", data)},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
            }

            catch (Exception ex)
            {
                masterConnected = false;
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}WriteMultipleRegistersAsync fail,startAddress:{startAddress},data:{string.Join(",",data)},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveName + ex.Message);
            }
        }

        /// <summary>
        /// 写从站多个寄存器值
        /// </summary>
        /// <param name="startAddress">起始地址</param>
        /// <param name="data">地址值数组</param>
        public async void WriteMultipleRegistersAsync(ushort startAddress, float[] data)
        {

            try
            {
               

                List<ushort> writeData = new List<ushort>();

                foreach (var item in data)
                {

                    ushort[] buff = new ushort[2];
                    SetReal(buff, 0, item);
                    writeData.AddRange(buff);

                }

                ushort[] registerBuffer = writeData.ToArray();
                if (master is null) return;
                await master.WriteMultipleRegistersAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, registerBuffer);
                logger.Info($"RTUMaster {ModbusRTUMasterInfo.SlaveName}WriteMultipleRegistersAsync,startAddress:{startAddress},data:{data},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
            }

            catch (Exception ex)
            {
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}WriteMultipleRegistersAsync fail,startAddress:{startAddress},data:{data},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveName + ex.Message);
            }
        }


        /// <summary>
        /// 写从站多个寄存器值
        /// </summary>
        /// <param name="startAddress">起始地址</param>
        /// <param name="data">地址值数组</param>
        public async void WriteMultipleRegistersAsyncABCD(ushort startAddress, float[] data)
        {

            try
            {


                List<ushort> writeData = new List<ushort>();

                foreach (var item in data)
                {

                    ushort[] buff = new ushort[2];
                    SetRealABCD(buff, 0, item);
                    writeData.AddRange(buff);

                }

                ushort[] registerBuffer = writeData.ToArray();
                if (master is null) return;
                await master.WriteMultipleRegistersAsync(ModbusRTUMasterInfo.SlaveAddr, startAddress, registerBuffer);
                logger.Info($"RTUMaster {ModbusRTUMasterInfo.SlaveName}WriteMultipleRegistersAsync,startAddress:{startAddress},data:{data},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
            }

            catch (Exception ex)
            {
                masterConnected = false;
                logger.Error($"RTUMaster {ModbusRTUMasterInfo.SlaveName}WriteMultipleRegistersAsync fail,startAddress:{startAddress},data:{data},port:{ModbusRTUMasterInfo.Port},slaveName:{ModbusRTUMasterInfo.SlaveName}");
                MasterErrorEvent?.Invoke(this, ModbusRTUMasterInfo.SlaveName + ex.Message);
            }
        }

        /// <summary>
        /// 赋值string
        /// </summary>
        /// <param name="src"></param>
        /// <param name="start"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static  void SetString(ushort[] src, ushort start, string value)
        {
            byte[] bytesTemp = Encoding.UTF8.GetBytes(value);
            ushort[] dest = Bytes2Ushorts(bytesTemp);
            dest.CopyTo(src, start);
        }

        /// <summary>
        /// 赋值string
        /// </summary>
        /// <param name="src"></param>
        /// <param name="start"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static ushort[] SetString( ushort start, string value)
        {
            byte[] bytesTemp = Encoding.UTF8.GetBytes(value);
            ushort[] dest = Bytes2Ushorts(bytesTemp);
            return dest;
        }

        /// <summary>
        /// 写字符串
        /// </summary>
        /// <param name="startAddr"></param>
        /// <param name="value"></param>
        public void WriteString(ushort startAddr, string value)
        {
            
            var src = SetString(startAddr, value);
            WriteMultipleRegistersAsync(startAddr, src);
        }

       /// <summary>
       /// 清除字符串
       /// </summary>
       /// <param name="startAddr">开始地址</param>
       /// <param name="len">长度</param>
        public void ClearString(ushort startAddr, ushort len=17)
        {

            ushort[] src = new ushort[len];
            WriteMultipleRegistersAsync(startAddr, src);
        }

        /// <summary>
        /// 获取string
        /// </summary>
        /// <param name="src"></param>
        /// <param name="start"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string GetString(ushort[] src, int start, int len)
        {
            ushort[] temp = new ushort[len];
            for (int i = 0; i < len; i++)
            {
                temp[i] = src[i + start];
            }
            byte[] bytesTemp = Ushorts2Bytes(temp);
            string res = Encoding.UTF8.GetString(bytesTemp).Trim(new char[] { '\0' });
            return res;
        }

        /// <summary>
        /// 获取string
        /// </summary>
        /// <param name="src"></param>
        /// <param name="start"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public async Task<string?> ReadString(ushort startAddr, ushort len)
        {
            //先读取ushort字符上来
            
            var src = await ReadHoldingRegistersAsync(startAddr, len);

            if (src is null)
            {
                return null;
            }
            
            byte[] bytesTemp = Ushorts2Bytes(src);
            string res = Encoding.UTF8.GetString(bytesTemp).Trim(new char[] { '\0' });
            return res;
        }

        /// <summary>
        /// 赋值Real类型数据
        /// </summary>
        /// <param name="src"></param>
        /// <param name="start"></param>
        /// <param name="value"></param>
        public static void SetReal(ushort[] src, int start, float value)
        {
            byte[] bytes = BitConverter.GetBytes(value);

            ushort[] dest = Bytes2Ushorts(bytes);

            dest.CopyTo(src, start);
        }

        /// <summary>
        /// 赋值Real类型数据
        /// </summary>
        /// <param name="src"></param>
        /// <param name="start"></param>
        /// <param name="value"></param>
        public static void SetRealABCD(ushort[] src, int start, float value)
        {
            byte[] bytes = SwapEndianness(BitConverter.GetBytes(value));

            
            ushort[] dest = Bytes2Ushorts(bytes);

            dest.CopyTo(src, start);
        }
        /// <summary>
        /// 交互高低字节
        /// </summary>
        /// <param name="array"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException"></exception>
        public static byte[] SwapEndianness(byte[] array)
        {
            if (array == null)
                throw new ArgumentNullException("array");

            if (array.Length % 2 != 0)
            {
                throw new ArgumentException("Invalid array length", "array");
            }
                

            var result = new byte[array.Length];
            for (int i = 0; i+2 < array.Length; i++)
            {
                result[i] = array[i + 2];
                result[i + 2] = array[i];
            }
            return result;
        }

        /// <summary>
        /// 获取float类型数据
        /// </summary>
        /// <param name="src"></param>
        /// <param name="start"></param>
        /// <returns></returns>
        public static float GetReal(ushort[] src, int start)
        {
            ushort[] temp = new ushort[2];
            for (int i = 0; i < 2; i++)
            {
                temp[i] = src[i + start];
            }
            byte[] bytesTemp = Ushorts2Bytes(temp);
            float res = BitConverter.ToSingle(bytesTemp, 0);
            return res;
        }

        /// <summary>
        /// 获取float类型数据
        /// </summary>
        /// <param name="src"></param>
        /// <param name="start"></param>
        /// <returns></returns>
        public static float GetRealABCD(ushort[] src, int start)
        {
            ushort[] temp = new ushort[2];
            //for (int i = 1; i < 0; i--)
            //{
            //    temp[i] = src[i + start];
            //}
            temp[0] = src[1 + start];
            temp[1] = src[0 + start];
            byte[] bytesTemp = Ushorts2Bytes(temp);
            float res = BitConverter.ToSingle(bytesTemp, 0);
            return res;
        }

        /// <summary>
        /// 赋值Short类型数据
        /// </summary>
        /// <param name="src"></param>
        /// <param name="start"></param>
        /// <param name="value"></param>
        public static void SetShort(ushort[] src, int start, short value)
        {
            byte[] bytes = BitConverter.GetBytes(value);

            ushort[] dest = Bytes2Ushorts(bytes);

            dest.CopyTo(src, start);
        }

        /// <summary>
        /// 获取short类型数据
        /// </summary>
        /// <param name="src"></param>
        /// <param name="start"></param>
        /// <returns></returns>
        public static short GetShort(ushort[] src, int start)
        {
            ushort[] temp = new ushort[1];
            temp[0] = src[start];
            byte[] bytesTemp = Ushorts2Bytes(temp);
            short res = BitConverter.ToInt16(bytesTemp, 0);
            return res;
        }


        public static bool[] GetBools(ushort[] src, int start, int num)
        {
            ushort[] temp = new ushort[num];
            for (int i = start; i < start + num; i++)
            {
                temp[i] = src[i + start];
            }
            byte[] bytes = Ushorts2Bytes(temp);

            bool[] res = Bytes2Bools(bytes);

            return res;
        }

        private static bool[] Bytes2Bools(byte[] b)
        {
            bool[] array = new bool[8 * b.Length];

            for (int i = 0; i < b.Length; i++)
            {
                for (int j = 0; j < 8; j++)
                {
                    array[i * 8 + j] = (b[i] & 1) == 1;//判定byte的最后一位是否为1，若为1，则是true；否则是false
                    b[i] = (byte)(b[i] >> 1);//将byte右移一位
                }
            }
            return array;
        }

        private static byte Bools2Byte(bool[] array)
        {
            if (array != null && array.Length > 0)
            {
                byte b = 0;
                for (int i = 0; i < 8; i++)
                {
                    if (array[i])
                    {
                        byte nn = (byte)(1 << i);//左移一位，相当于×2
                        b += nn;
                    }
                }
                return b;
            }
            return 0;
        }

        private static ushort[] Bytes2Ushorts(byte[] src, bool reverse = false)
        {
            int len = src.Length;

            byte[] srcPlus = new byte[len + 1];
            src.CopyTo(srcPlus, 0);
            int count = len >> 1;

            if (len % 2 != 0)
            {
                count += 1;
            }

            ushort[] dest = new ushort[count];
            if (reverse)
            {
                for (int i = 0; i < count; i++)
                {
                    dest[i] = (ushort)(srcPlus[i * 2] << 8 | srcPlus[2 * i + 1] & 0xff);
                }
            }
            else
            {
                for (int i = 0; i < count; i++)
                {
                    dest[i] = (ushort)(srcPlus[i * 2] & 0xff | srcPlus[2 * i + 1] << 8);
                }
            }

            return dest;
        }

        private static byte[] Ushorts2Bytes(ushort[] src, bool reverse = false)
        {

            int count = src.Length;
            byte[] dest = new byte[count << 1];
            if (reverse)
            {
                for (int i = 0; i < count; i++)
                {
                    dest[i * 2] = (byte)(src[i] >> 8);
                    dest[i * 2 + 1] = (byte)(src[i] >> 0);
                }
            }
            else
            {
                for (int i = 0; i < count; i++)
                {
                    dest[i * 2] = (byte)(src[i] >> 0);
                    dest[i * 2 + 1] = (byte)(src[i] >> 8);
                }
            }
            return dest;
        }

        byte[] StringToByteArray(string hex)
        {
            if (hex.Length % 2 != 0)
            {
                hex = hex.Insert(hex.Length - 1, "0");
            }
            int length = hex.Length / 2;
            byte[] byteArray = new byte[length];

            for (int i = 0; i < length; i++)
            {
                byteArray[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
            }

            //if (byteArray.Length<2)
            //{
            //    byte[] byteArray2 = new byte[2];
            //    byteArray2[0] = 0;
            //    byteArray2[1] = byteArray[0];
            //    return byteArray2;
            //}
            
            return byteArray;
        }

        public void Dispose()
        {
            QueueStop = true;
            Disconnect();
            if (master !=null)
            {
                if (ModbusRTUMasterInfo is null || ModbusRTUMasterInfo.Port is null)
                {
                    return;
                }
                ModbusRTUMasterInfo?.Port.Close();
                master.Dispose();
            }
            logger.Error($"RTUMaster {ModbusRTUMasterInfo?.SlaveName}Dispose,port:{ModbusRTUMasterInfo?.Port},slaveName:{ModbusRTUMasterInfo?.SlaveName}");
        }
    }
}
